﻿import flash.geom.Point;
import flash.geom.Rectangle;
import mx.utils.Delegate;

import kliment.utils.MCC;

/**
 * ...
 * @author	Kliment
 * @version	0.1.0
 */

class kliment.controls.LoopScroll {
	private var _clocker:MovieClip;
	private var _target_mc:MovieClip;
	private var _clone_mc:MovieClip;
	private var _space_mc:MovieClip;
	private var _center:Point;
	private var _position:Point;
	private var _bounds:Object;
	public var focusBorder:Number = 0;
	
	public function LoopScroll(target_mc:MovieClip, clone_mc:MovieClip, space_mc:MovieClip) {
		_target_mc = target_mc;
		_clone_mc = clone_mc;
		_space_mc = space_mc;
		_clocker = MCC.create();
		_center = new Point(0, 0);
		_position = new Point(0, 0);
		_clocker.onEnterFrame = Delegate.create(this, _onEnterFrame);
	}
	
	private function _onEnterFrame():Void {
		_center.x = _space_mc._width / 2 + _space_mc._x;
		_center.y = _space_mc._height / 2 + _space_mc._y;
		_bounds = {
			xMin: -(_target_mc._width - _space_mc._width - _space_mc._x), 
			yMin: -(_target_mc._height - _space_mc._height - _space_mc._y), 
			xMax:_space_mc._x, 
			yMax:_space_mc._y
		};
		
		if ((_target_mc._width > _space_mc._width || _target_mc._height > _space_mc._height) && 
			_target_mc._parent._xmouse > _space_mc._x + focusBorder && 
			_target_mc._parent._xmouse < _space_mc._x + _space_mc._width - focusBorder*2 && 
			_target_mc._parent._ymouse > _space_mc._y + focusBorder && 
			_target_mc._parent._ymouse < _space_mc._y + _space_mc._height - focusBorder*2) {
			
			if (_target_mc._width > _space_mc._width){
				_position.x = Math.floor(_position.x - ((_target_mc._parent._xmouse - _center.x) / 30));
				
				if (_position.x > _target_mc._width)
					_position.x = _bounds.xMax;
				else 
				if (_position.x < -_target_mc._width)
					_position.x = _bounds.xMax;
					
				_clone_mc._y = _target_mc._y;
				_target_mc._x = _position.x;
					
				if (_position.x > _bounds.xMax) {
					_clone_mc._x = _target_mc._x - _clone_mc._width;
				} else 	
				if (_position.x < _bounds.xMax) {
					_clone_mc._x = _target_mc._x + _target_mc._width;
				}
			} else 
			if (_target_mc._height > _space_mc._height){
				_position.y = Math.floor(_position.y - ((_target_mc._parent._ymouse - _center.y) / 30));
				
				if (_position.y > _target_mc._height)
					_position.y = _bounds.yMax;
				else 
				if (_position.y < -_target_mc._height)
					_position.y = _bounds.xMax;
					
				_clone_mc._x = _target_mc._x;
				_target_mc._y = _position.y;
					
				if (_position.y > _bounds.yMax) {
					_clone_mc._y = _target_mc._y - _clone_mc._height;
				} else 
				if (_position.y < _bounds.yMax) {
					_clone_mc._y = _target_mc._y + _target_mc._height;
				}
			}		
		}
	}
	
}